package net.chathu.airgw.crypto 
{
	import air.net.SocketMonitor;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	/**
	 * ...
	 * @author ze
	 */
	public class SecuredSocket 
	{
		
		protected var cipherInputStream:CipherInputStream;
		protected var cipherOutputStream:CipherOutputStream;
		protected var socket:Socket;
	
		public function SecuredSocket(socket:Socket, cipher:Cipher, flag:Boolean) {
			this.socket = socket;
			// InputStream inputstream = socket.getInputStream();
			// OutputStream outputstream = socket.getOutputStream();
			//Cipher d2 = cipher.copy();
			var d2:Cipher = cipher.copy();
			if (flag) { //ha mi allitjuk be a kulcsot
				//byte abyte0[];
				var abyte0:Array;
				if ((abyte0 = cipher.generateKey()).length > 0)
				{
					//outputstream.write(abyte0, 0, abyte0.length);
					var bytearray:ByteArray = new ByteArray();
					for (var c:int = 0; c < abyte0.length; c++)
					{
						bytearray.writeByte(abyte0[c]);
					}
					socket.writeBytes(bytearray, 0, abyte0.length);
				}
				d2.setKey(abyte0);
			} else { //ha ugy olvassuk a kulcsot
				//byte abyte1[] = new byte[cipher.b()];
				var abyte1:Array = new Array();
				var keylength:int = cipher.getSeedLen();
				//trace("key length:" + keylength);
				for (var cc:int = 0; cc < keylength; cc++)
				{
					abyte1[cc] = 0;
				}
				if (keylength > 0) {
					var keyReadSuccess:Boolean = false;
					var bytearray2:ByteArray = new ByteArray();
					while (!keyReadSuccess)
					{
						try {
							socket.readBytes(bytearray2, bytearray2.position, keylength - bytearray2.position);
							//ByteArrayDump.dump(bytearray2);
							//trace("Pos after read:" + bytearray2.position);
							if (bytearray2.bytesAvailable >= keylength)
							{
								//trace("read success");
								keyReadSuccess = true;
								bytearray2.position = 0;
								for (var ccc:int = 0; ccc < keylength; ccc++)
								{
									abyte1[ccc] = bytearray2.readByte();
								}
							}
							
						} catch (err:Error) {
							trace("error: "+ err.message);
							throw err;
						}
					}

					cipher.setKey(abyte1);
					d2.setKey(abyte1);
				}
			}
			cipherInputStream = new CipherInputStream(socket, cipher);
			cipherOutputStream = new CipherOutputStream(socket, d2);
		}
		
		public final function getInputStream():CipherInputStream{
			return cipherInputStream;
		}

		public final function getOutputStream():CipherOutputStream {
			return cipherOutputStream;
		}
		
		public function flush():void
		{
			socket.flush();
		}
		
		public function get connected():Boolean {
			return socket.connected;
		}

	}

}